package com.dule.Medic.pages;

import org.apache.tapestry5.annotations.CleanupRender;
import org.apache.tapestry5.annotations.InjectComponent;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionState;
import org.apache.tapestry5.corelib.components.Zone;
import org.apache.tapestry5.ioc.annotations.Inject;

import com.dule.Medic.beans.MedEntryBean;
import com.dule.Medic.model.Doctor;
import com.dule.Medic.model.MedEntry;
import com.dule.Medic.model.Patient;
import com.dule.Medic.service.DoctorService;
import com.dule.Medic.service.MedEntryService;
import com.dule.Medic.service.PatientService;

public class ExaminePatient 
{
	@SessionState 
	@Property    
	private Doctor doctor;    
	private boolean doctorExists;          
	
	@SessionState
	@Property
	private Patient patient;
	private boolean patientExists;
	
	@SessionState
	@Property
	private MedEntry medentry;
	
	@SuppressWarnings("unused")
	@Property
	@Persist
	private String message; 
	
	@InjectComponent
	@Property
	private Zone MedEntriesTable;
	
	@SuppressWarnings("unused")
	@Property
	@Persist("flash")
	private boolean condition; 
	
	@Inject       
	private PatientService patientservice; 
	@Inject       
	private DoctorService doctorservice; 
	@Inject       
	private MedEntryService medentryservice; 
	
	public Object onActivate()
	{    
		if(doctorExists)
		{
			if(patientExists)
			{
				doctor.getMedEntries().size();	//because lazy loading 
				patient.getMedEntries().size(); 
				medentry= new MedEntryBean();
				return null;
			}
			else
			{
				return Index.class;
			}
		}
		
		return FirstPage.class;   
	}
	@OnEvent(component="deleteMedEntry")
    public Object OnDeleteMedEntry(Long Id)
    {
		medentry=medentryservice.retrieveOne(Id);
		doctor.RemoveMedEntry(medentry);
		doctorservice.update(doctor);
		patient.RemoveMedEntry(medentry);
		patientservice.update(patient);
		medentryservice.delete(medentry);
		message="Medical Entry has been successfully removed.";
		return MedEntriesTable.getBody();
		
    } 
	
	@OnEvent(component="changemedentry")
    public Object OnChangeMedEntry(Long Id)
    {
		medentry= medentryservice.retrieveOne(Id);
		if(medentry.getDoctor().getId().equals(doctor.getId()))
		{
			medentry.getPrescriptions().size();
			return ChangeMedEntryData.class;
		}
		else
		{
			message="This Medical Entry cannot be modified because it is added by another doctor!!!!!!";
			return this;
		}
		
    } 
	
	public void SetPatient(Patient patient)
	{
		this.patient=patient;
	}
	
	public boolean isCondition() 
	{
		return medentry.getDoctor().getId().equals(doctor.getId());
	}
	
	@CleanupRender     
	public void cleanUp()
	{             
		message =null;        
	}  
	
}
